
import { getQiNiuToken } from '@/api/common';
import * as qiniu from 'qiniu-js'

export function compressFile(file){
  const options = {
    quality: 0.6,
    noCompressIfLarger: true
    // maxWidth: 1000,
    // maxHeight: 618
  }
  return new Promise((rev, rej) => qiniu.compressImage(file, options).then(rev).catch(rej))
}

// https://developer.qiniu.com/kodo/1283/javascript
export async function originUpload(file, compress = true){
  const token = await getQiNiuToken({});
  let source = file;
  if (compress) {
    const files = await compressFile(file);
    source = files?.dist;
  }
  return new Promise((rev, rej) => {
    if (token) {
      // const key = `icodeicode/${(new Date()).valueOf()}`
      const key = `icodeicode/${file.name}`
      const observable = qiniu.upload(source, key, token, {
        fname: file.name,
        params: {},
        mimeType: file.type,
      })
      const subscription = observable.subscribe(proccess => {
        console.log('next', proccess);
      },
      (QiniuError, QiniuRequestError, QiniuNetworkError) => {
        console.log('error', QiniuError, QiniuRequestError, QiniuNetworkError);
        rej(QiniuError)
      },
      (results) => {
        console.log('complete', results, file);
        rev({ url: `${import.meta.env.VITE_QINIU_URL}/${results.key}`?.trim(), name: file.name })
      })
      console.log('subscription', subscription);
    } else {
      rej('缺少token')
    }
  });
}

// https://developer.qiniu.com/kodo/1283/javascript
export async function getWatermarkImgimage(image, text = 'icodeicode'){
  return new Promise(async (rev, rej) => {
    if (!image) {
      rev(null);
    }
    try {
      const imgLink = qiniu.watermark({
        mode: 2,  // 文字水印
        text, // 水印文字，mode = 2 时 **必需**
        dissolve: 90,          // 透明度，取值范围1-100，非必需，下同
        gravity: 'SouthWest',  // 水印位置，同上
        fontsize: 500,         // 字体大小，单位: 缇
        font: '黑体',           // 水印文字字体
        dx: 0,               // 横轴边距，单位:像素(px)
        dy: 0,               // 纵轴边距，单位:像素(px)
        fill: '#000'        // 水印文字颜色，RGB格式，可以是颜色名称
      }, null, null)
      rev(`${image}?${imgLink}`)
    } catch (error) {
      rev(image)
    }
  })
}
